<?php
namespace app\api\middleware;

use think\facade\Request;
use think\facade\Cache;
use think\facade\DB;
use app\common\utils\JsonResponse;

class Auth
{
    // 不需要登录的路由
    protected $excludeRoutes = [
        '/api/user/login',  // 登录
        '/api/user/register', // 注册
        '/api/index/index',  // 首页
    ];

    public function handle($request, \Closure $next)
    {
        // 获取当前路由
        $path = Request::pathinfo();
        
        // 判断是否需要登录
        if (!in_array('/' . $path, $this->excludeRoutes)) {
            // 获取token
            $token = Request::header('Authorization');
            if (empty($token)) {
                return JsonResponse::error('请先登录', 401);
            }
            $token = preg_replace('/Bearer\s/', '', $token);
            if(!$token){
                return JsonResponse::error('请先登录', 401);//exit(json_encode(['code'=>401,'msg'=>'token不能为空！']));
            }
            // 验证token
            $userId = Cache::get('user_token_' . $token);
            if (empty($userId)) {
                //检测user_token表 ->where('status',1)
                $userToken = Db::name('user_token')->where('token', $token)->find();
                if(empty($userToken)){
                    return JsonResponse::error('登录已过期', 401);
                }else if($userToken && $userToken['expire_time']>time() && $userToken['status'] == 1){
                    $userId = $userToken['user_id'];
                    $t = $userToken['expire_time']-time();
                    Cache::set('user_token_' . $token, $userId, $t);
                }else{
                    return JsonResponse::error('登录已过期', 401);
                }
            }
            // 将用户ID保存到请求对象中
            $request->userId = $userId;
            // 绑定到容器(可选)
            bind('userId', $userId);
        }
        
        return $next($request);
    }
} 